<script setup>
import { ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useChatStore } from '@/stores/chat'
import BaseLayout from '@/layouts/BaseLayout.vue'
import ChatMessage from '@/components/ChatMessage.vue'
import { ElMessage } from 'element-plus'

const chatStore = useChatStore()
const { currentConversation, isLoading, error, sidebarCollapsed, currentModel, conversations } = storeToRefs(chatStore)
const inputMessage = ref('')
const textarea = ref(null)
const messagesContainer = ref(null)
const showScrollButton = ref(false)

const createNewChat = () => {
  chatStore.createNewChat()
}

const selectConversation = (conversationId) => {
  chatStore.selectConversation(conversationId)
}

// 监听消息容器的滚动事件
const handleScroll = () => {
  if (!messagesContainer.value) return
  const { scrollTop, scrollHeight, clientHeight } = messagesContainer.value
  // 如果距离底部超过200px就显示按钮
  showScrollButton.value = scrollHeight - scrollTop - clientHeight > 200
}

// 滚动到底部
const scrollToBottom = () => {
  if (!messagesContainer.value) return

  const container = messagesContainer.value
  const targetScroll = container.scrollHeight
  const startScroll = container.scrollTop
  const distance = targetScroll - startScroll

  // 使用 requestAnimationFrame 实现平滑滚动
  const duration = 500 // 滚动持续时间（毫秒）
  const startTime = performance.now()

  function animate(currentTime) {
    const elapsed = currentTime - startTime
    const progress = Math.min(elapsed / duration, 1)

    // 使用 easeInOutCubic 缓动函数
    const easing = progress < 0.5
      ? 4 * progress * progress * progress
      : 1 - Math.pow(-2 * progress + 2, 3) / 2

    container.scrollTop = startScroll + (distance * easing)

    if (progress < 1) {
      requestAnimationFrame(animate)
    }
  }

  requestAnimationFrame(animate)
}

// 监听消息变化，自动滚动到底部
watch(() => currentConversation.value?.messages, () => {
  if (isLoading.value) {
    scrollToBottom()
  }
}, { deep: true })

const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return

  const message = {
    role: 'user',
    content: inputMessage.value,
    timestamp: new Date().toISOString()
  }

  inputMessage.value = ''
  if (textarea.value) {
    textarea.value.style.height = 'auto'
  }

  await chatStore.addMessage(message)
}

const useExample = (text) => {
  inputMessage.value = text
  sendMessage()
}

const autoResize = () => {
  const el = textarea.value
  if (!el) return

  el.style.height = 'auto'
  el.style.height = el.scrollHeight + 'px'
}

// 添加重新生成函数
const regenerateResponse = async () => {
  if (isLoading.value) return

  try {
    // 移除最后一条 AI 回复
    if (currentConversation.value?.messages.length > 0) {
      const messages = currentConversation.value.messages
      const lastMessage = messages[messages.length - 1]
      if (lastMessage.role === 'assistant') {
        await chatStore.removeLastMessage()
        await chatStore.generateResponse()
      }
    }
  } catch (err) {
    console.error('Regenerate response error:', err)
    ElMessage({
      message: '重新生成失败，请重试',
      type: 'error',
      duration: 2000,
      offset: 60
    })
  }
}

const switchModel = () => {
  chatStore.switchModel()
}
</script>

<template>
  <BaseLayout>
    <div class="chat-container">
      <div class="sidebar" :class="{ 'sidebar-collapsed': sidebarCollapsed }">
        <button @click="createNewChat" class="new-chat-button">
          <svg viewBox="0 0 24 24" class="new-chat-icon">
            <path fill="currentColor" d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
          </svg>
          新建会话
        </button>
        
        <div class="conversation-list">
          <div v-for="conv in conversations" 
               :key="conv.id" 
               :class="['conversation-item', { active: currentConversation?.id === conv.id }]"
               @click="selectConversation(conv.id)">
            <span class="conversation-title">{{ conv.title }}</span>
            <button class="delete-button" @click.stop="chatStore.deleteConversation(conv.id)">
              <svg viewBox="0 0 24 24" class="delete-icon">
                <path fill="currentColor" d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
              </svg>
            </button>
          </div>
        </div>
      </div>

      <div class="main-content">
        <button @click="switchModel" class="model-switch-button">
          当前模型: {{ currentModel }}
        </button>
        <!-- 滚动按钮 -->
        <button v-show="showScrollButton" class="scroll-button" @click="scrollToBottom">
          <svg viewBox="0 0 24 24" class="scroll-icon">
            <path fill="currentColor" d="M12 16l-6-6h12z" />
          </svg>
        </button>
        <!-- 欢迎页面 -->
        <div v-if="!currentConversation?.messages.length" class="welcome-screen">
          <h1>有什么可以帮忙的?</h1>
        </div>

        <!-- 聊天消息区域 -->
        <div v-else ref="messagesContainer" class="messages" @scroll="handleScroll">
          <ChatMessage v-for="message in currentConversation?.messages" :key="message.timestamp" :message="message"
            @regenerate="regenerateResponse" />
          <div v-if="isLoading" class="loading-message">
            AI正在思考...
          </div>
          <div v-if="error" class="error-message">
            {{ error }}
          </div>
        </div>

        <!-- 输入区域 -->
        <div :class="[
          'input-container',
          !currentConversation?.messages.length ? 'input-container-centered' : '',
          sidebarCollapsed ? 'sidebar-collapsed' : ''
        ]">
          <div class="input-wrapper">
            <textarea v-model="inputMessage" @keydown.enter.prevent="sendMessage" placeholder="给 ChatGPT 发送消息" rows="1"
              ref="textarea" @input="autoResize"></textarea>
            <button @click="sendMessage" class="send-button" :disabled="!inputMessage.trim() || isLoading">
              <svg viewBox="0 0 24 24" class="send-icon">
                <path fill="currentColor" d="M3 20v-6l8-2-8-2V4l19 8z" />
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>
  </BaseLayout>
</template>

<style scoped>
.chat-container {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.main-content {
  width: 100%;
  max-width: 48rem;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 1rem;
  position: relative;
}

.messages {
  flex: 1;
  width: 100%;
  overflow-y: auto;
  padding-bottom: 120px;
}

.welcome-screen {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
}

.welcome-screen h1 {
  margin-bottom: 2rem;
  color: var(--text-primary);
}

.input-container {
  position: fixed;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 100%;
  max-width: 48rem;
  padding: 1.5rem;
  background: var(--primary-bg);
  z-index: 10;
}

.input-container.input-container-centered {
  position: fixed;
  top: 50%;
  transform: translate(-50%, -50%);
}

.input-wrapper {
  background: var(--secondary-bg);
  border-radius: 0.75rem;
  padding: 0.75rem;
  display: flex;
  align-items: flex-end;
  gap: 0.5rem;
  border: 1px solid var(--border-color);
  pointer-events: auto;
  width: 100%;
  position: relative;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.input-wrapper textarea {
  flex: 1;
  background: transparent;
  border: none;
  color: var(--text-primary);
  font-size: 1rem;
  line-height: 1.5;
  max-height: 200px;
  min-height: 24px;
  outline: none;
  padding: 0;
  resize: none;
  font-family: inherit;
}

.input-wrapper textarea::placeholder {
  color: var(--text-secondary);
}

.input-container-centered {
  bottom: 50%;
  transform: translate(-50%, 50%);
}

.send-button {
  background: transparent;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  padding: 0.25rem;
  height: 24px;
  width: 24px;
  border-radius: 0.25rem;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.send-button:hover:not(:disabled) {
  color: var(--text-primary);
  background: rgba(255, 255, 255, 0.1);
}

.send-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.send-icon {
  width: 16px;
  height: 16px;
}

/* 添加主题相关样式 */
:root[data-theme="light"] {
  .input-wrapper {
    background: #ffffff;
    border: 1px solid var(--border-color-light);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  }

  .input-wrapper textarea {
    color: var(--text-primary-light);
  }

  .input-wrapper textarea::placeholder {
    color: var(--text-secondary-light);
  }

  .send-button {
    color: var(--text-secondary-light);
  }

  .send-button:hover:not(:disabled) {
    color: var(--text-primary-light);
    background: rgba(0, 0, 0, 0.05);
  }
}

:root[data-theme="dark"] {
  .input-wrapper {
    background: var(--secondary-bg-dark);
    border: 1px solid var(--border-color-dark);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
  }

  .input-wrapper textarea {
    color: var(--text-primary-dark);
  }

  .input-wrapper textarea::placeholder {
    color: var(--text-secondary-dark);
  }

  .send-button {
    color: var(--text-secondary-dark);
  }

  .send-button:hover:not(:disabled) {
    color: var(--text-primary-dark);
    background: rgba(255, 255, 255, 0.1);
  }
}

.loading-message {
  padding: 1rem;
  text-align: center;
  color: var(--text-secondary);
}

.error-message {
  padding: 1rem;
  text-align: center;
  color: #ff4444;
  background-color: rgba(255, 68, 68, 0.1);
}

.scroll-button {
  position: fixed;
  right: 20px;
  bottom: 120px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: var(--secondary-bg);
  border: 1px solid var(--border-color);
  color: var(--text-primary);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 1000;
  transition: all 0.2s;
  opacity: 0.8;
}

.scroll-button:hover {
  opacity: 1;
  transform: scale(1.1);
}

.scroll-icon {
  width: 20px;
  height: 20px;
}

.model-switch-button {
  margin-bottom: 1rem;
  padding: 0.5rem 1rem;
  background-color: var(--button-primary);
  color: white;
  border: none;
  border-radius: 0.5rem;
  cursor: pointer;
}

.sidebar {
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  width: 260px;
  background: var(--secondary-bg);
  border-right: 1px solid var(--border-color);
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
  z-index: 100;
}

.sidebar-collapsed {
  width: 0;
  border-right: none;
}

.new-chat-button {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin: 1rem;
  padding: 0.75rem;
  background: var(--button-primary);
  border: none;
  border-radius: 0.5rem;
  color: white;
  cursor: pointer;
  transition: all 0.2s;
  width: calc(100% - 2rem);
}

.new-chat-button:hover {
  background: var(--button-hover);
}

.new-chat-icon {
  width: 1.25rem;
  height: 1.25rem;
}

.conversation-list {
  flex: 1;
  overflow-y: auto;
  padding: 0.5rem;
}

.conversation-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.75rem;
  border-radius: 0.5rem;
  cursor: pointer;
  transition: all 0.2s;
  color: var(--text-primary);
  margin-bottom: 0.25rem;
}

.conversation-item:hover {
  background: rgba(255, 255, 255, 0.1);
}

.conversation-item.active {
  background: rgba(255, 255, 255, 0.15);
}

.conversation-title {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 0.5rem;
}

.delete-button {
  padding: 0.25rem;
  background: transparent;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  opacity: 0;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 0.25rem;
}

.conversation-item:hover .delete-button {
  opacity: 1;
}

.delete-button:hover {
  background: rgba(255, 255, 255, 0.1);
  color: var(--text-primary);
}

.delete-icon {
  width: 1rem;
  height: 1rem;
}

.main-content {
  margin-left: 260px;
  transition: all 0.3s ease;
  width: calc(100% - 260px);
}

.sidebar-collapsed + .main-content {
  margin-left: 0;
  width: 100%;
}

/* 适配浅色主题 */
:root[data-theme="light"] {
  .conversation-item:hover {
    background: rgba(0, 0, 0, 0.05);
  }

  .conversation-item.active {
    background: rgba(0, 0, 0, 0.08);
  }

  .delete-button:hover {
    background: rgba(0, 0, 0, 0.05);
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .main-content {
    padding: 0.5rem;
  }

  .input-container {
    padding: 0.75rem;
  }

  .messages {
    padding-bottom: 100px;
  }
}
</style>